package com.yomahub.tlog.web.filter;

import com.yomahub.tlog.constant.TLogConstants;
import com.yomahub.tlog.context.TLogContext;
import com.yomahub.tlog.web.common.TLogWebCommon;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 支持servlet
 *
 * @author Bryan.Zhang
 * @since 1.3.5
 */
public class TLogServletFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            try {
                HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                TLogWebCommon.loadInstance().preHandle(httpServletRequest);
                // 把traceId放入response的header，为了方便有些人有这样的需求，从前端拿整条链路的traceId
                httpServletResponse.addHeader(TLogConstants.TLOG_TRACE_KEY, TLogContext.getTraceId());
                final TLogHeaderRequestWrapper tLogHeaderRequestWrapper = gettLogHeaderRequestWrapper(
                        httpServletRequest);
                chain.doFilter(tLogHeaderRequestWrapper, httpServletResponse);
                return;
            }
            finally {
                TLogWebCommon.loadInstance().afterCompletion();
            }
        }
        chain.doFilter(request, response);
    }

    private TLogHeaderRequestWrapper gettLogHeaderRequestWrapper(
            HttpServletRequest httpServletRequest) {
        TLogHeaderRequestWrapper tLogHeaderRequestWrapper = new TLogHeaderRequestWrapper(httpServletRequest);
        tLogHeaderRequestWrapper.putHeader(TLogConstants.TLOG_TRACE_KEY, TLogContext.getTraceId());
        tLogHeaderRequestWrapper.putHeader(TLogConstants.TLOG_SPANID_KEY, TLogContext.getSpanId());
        tLogHeaderRequestWrapper.putHeader(TLogConstants.PRE_IVK_APP_KEY, TLogContext.getPreIvkApp());
        tLogHeaderRequestWrapper.putHeader(TLogConstants.PRE_IVK_APP_HOST, TLogContext.getPreIvkHost());
        tLogHeaderRequestWrapper.putHeader(TLogConstants.PRE_IP_KEY, TLogContext.getPreIp());
        return tLogHeaderRequestWrapper;
    }

    @Override
    public void destroy() {

    }

}
